class Solution {
public:
    int left = 0, right = 0, k = 0;
    vector<string> ret;
    string path;
    vector<string> generateParenthesis(int n) {
        k = n;
        dfs();
        return ret;
    }

    void dfs()
    {
        if (left == right && left == k && right == k)
        {
            ret.push_back(path);
            return;
        }

        if (left >= right && left < k)
        {
            ++left;
            path += "(";
            dfs();
            --left;
            path.pop_back();

            ++right;
            path += ")";
            dfs();
            --right;
            path.pop_back();
        }
        else if (left >= right && left == k)
        {
            ++right;
            path += ")";
            dfs();
            --right;
            path.pop_back();
        }

    }
};